package com.chushouya.manager.service.admin.impl;

import com.general.framework.core.enums.StatusEnum;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Longs;
import com.general.framework.core.schema.PageResult;
import com.chushouya.manager.dao.entity.RegionEntity;
import com.chushouya.manager.dao.entity.VisitAreaEntity;
import com.chushouya.manager.dao.repository.RegionRepository;
import com.chushouya.manager.dao.repository.VisitAreaRepository;
import com.chushouya.manager.dto.admin.region.RegionQuery;
import com.chushouya.manager.dto.admin.visitarea.VisitAreaDTO;
import com.chushouya.manager.dto.admin.visitarea.VisitAreaListDTO;
import com.chushouya.manager.dto.admin.visitarea.VisitAreaQuery;
import com.chushouya.manager.dto.admin.visitarea.VisitAreaSaveDTO;
import com.chushouya.manager.service.admin.VisitAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class VisitAreaServiceImpl implements VisitAreaService {

    @Resource
    private VisitAreaRepository visitAreaRepository;

    @Resource
    private RegionRepository regionRepository;

    @Override
    public List<VisitAreaListDTO> selectVisitAreaList(VisitAreaQuery visitAreaQuery) {
        PageResult<VisitAreaEntity> pageResult = visitAreaRepository.selectPage(visitAreaQuery);
        List<VisitAreaEntity> rows = pageResult.getRows();
        
        // 使用Stream按cityCode分组，并聚合district列表
        return rows.stream()
                .collect(java.util.stream.Collectors.groupingBy(
                    VisitAreaEntity::getCityCode,
                    java.util.stream.Collectors.toList()
                ))
                .entrySet().stream()
                .map(entry -> {
                    Long cityCode = entry.getKey();
                    List<VisitAreaEntity> cityEntities = entry.getValue();
                    
                    // 取第一个实体作为基础信息（城市信息相同）
                    VisitAreaEntity firstEntity = cityEntities.get(0);
                    
                    // 创建DTO并设置基础信息
                    VisitAreaListDTO visitAreaDTO = new VisitAreaListDTO();
                    visitAreaDTO.setCityCode(cityCode);
                    visitAreaDTO.setCity(firstEntity.getCity());
                    
                    // 聚合所有区域名称
                    List<String> districtList = cityEntities.stream()
                            .map(VisitAreaEntity::getDistrict)
                            .filter(Objects::nonNull)
                            .distinct()
                            .collect(java.util.stream.Collectors.toList());
                    
                    visitAreaDTO.setDistrictList(districtList);
                    return visitAreaDTO;
                })
                .sorted((a, b) -> Long.compare(a.getCityCode(), b.getCityCode()))
                .collect(java.util.stream.Collectors.toList());
    }

    @Override
    public VisitAreaDTO selectVisitArea(Long cityCode) {
        VisitAreaQuery query = new VisitAreaQuery();
        query.setCityCode(cityCode);
        List<VisitAreaEntity> visitAreaList = visitAreaRepository.selectList(query);
        if (!visitAreaList.isEmpty()) {
            VisitAreaDTO visitAreaDTO = Beans.copy(visitAreaList.get(0), VisitAreaDTO.class);
            List<Long> areaCodeList = Lists.newArrayList();
            visitAreaList.forEach(visitAreaEntity -> {
                areaCodeList.add(visitAreaEntity.getDistrictCode());
            });
            visitAreaDTO.setVisitAreaList(areaCodeList);
            return visitAreaDTO;
        }
        return null;
    }

    @Override
    public void saveVisitArea(VisitAreaSaveDTO visitAreaDTO) {
        final Long cityCode = visitAreaDTO.getCityCode();
        final List<Long> visitAreaList = visitAreaDTO.getVisitAreaList();

        if (Longs.isNullOrZero(cityCode)) {
            throw Ex.business("城市编码不能为空，请选择城市");
        }
        this.deleteVisitArea(cityCode);
        RegionQuery query = new RegionQuery();
        query.setDistrictCodeList(visitAreaList);
        List<RegionEntity> regionList = regionRepository.selectList(query);

        List<VisitAreaEntity> list = Lists.newArrayList();

        regionList.forEach(regionEntity -> {
            VisitAreaEntity visitAreaEntity = new VisitAreaEntity();
            visitAreaEntity.setCityCode(cityCode);
            visitAreaEntity.setDistrict(regionEntity.getDistrict());
            visitAreaEntity.setDistrictCode(regionEntity.getDistrictCode());
            visitAreaEntity.setStatus(StatusEnum.normal.value());
            visitAreaEntity.setCreateTime(Dates.getTimeNow());
            visitAreaEntity.setUpdateTime(Dates.getTimeNow());
            visitAreaEntity.setProvinceCode(regionEntity.getProvinceCode());
            visitAreaEntity.setProvince(regionEntity.getProvince());
            visitAreaEntity.setCity(regionEntity.getCity());
            list.add(visitAreaEntity);
        });
        visitAreaRepository.insertList(list);
    }

    /**
     * 删除该城市下的所有上门区域
     */
    private void deleteVisitArea(Long cityCode) {
        visitAreaRepository.deleteByCityCode(cityCode);
    }
}
